﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Bronze.XXT.PhoneServer
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
		}

		private void btnStart_Click(object sender, EventArgs e)
		{
			//3分钟的超时时间
			var server = new Server(12122);
			server.SendTimeout = 60 * 3;
			server.ConnectionTimeout = 60 * 2;
			server.ActiveTestInterval = 60 * 6;
			server.MaxRetryCount = 0;
			server.KillConnectionMode = KillConnectionMode.ClientQueryConnectStatusKeepAliveTimeOut;
			server.KeepAliveTimeout = Convert.ToInt32(txtKeepAliveTimeout.Value);
			server.ReceiveData += new SocketHandle(server_ReceiveData);
			server.ClientClose += new SocketHandle(server_ClientClose);
			server.ClientConnect += new SocketHandle(server_ClientConnect);

			if (this.btnStart.Text.Equals("开启服务"))
			{
				try
				{
					BLL.Telephone.SetAllPhoneOffLine(); //设置所有话机离线
				}
				catch (Exception ex)
				{
					
				}
			}
			server.Start();
			btnStart.Text = "停止服务";
		}

		void server_ClientConnect(object sender, PhoneEventArgs e)
		{

		}

		void server_ClientClose(object sender, PhoneEventArgs e)
		{
			string strDeviceID = string.Empty;
			this.UpdateUI(() =>
			              {
			              	var conn = FindConn(e.Client.ConnectionId);
			              	if (conn != null)
			              	{
			              		conn.Text = "[离线]" + conn.Device_id + "(" + conn.Id + ")";
			              		strDeviceID = conn.Device_id;
			              	}
			              	string info = e.Infomation ?? "自动";
			              	this.listPhone.RefreshItems();
			              	this.listInfo.Items.Add(string.Format("[{0}]关闭连接:{1},{2}", info, e.Client.ConnectionId, DateTime.Now));
			              });
			if(!string.IsNullOrEmpty(strDeviceID))
			{
				try
				{
					BLL.Telephone.SetPhoneConnectStatus(2, strDeviceID);
				}
				catch (Exception ex)
				{
					Server.log.Error("发生错误，话机离线状态设置失败！", ex);
				}
			}
		}

		void server_ReceiveData(object sender, PhoneEventArgs e)
		{
			if (e.Data is Message)
			{
				var msg = e.Data as Message;
				if (msg.Body == null) return;

				if (msg.Body is STDT_SIGN_RECS_Request)
				{
					var cardInfo = msg.Body as STDT_SIGN_RECS_Request;
					var info = string.Format("({2})收到刷卡，卡号：{0} 时间:{1}", cardInfo.CardID.Trim(), cardInfo.start_time, e.Client.ConnectionId);
					this.UpdateUI(() => { this.listInfo.Items.Add(info); });

				}
				if (msg.Body is PHONE_AUTHEN_Request)
				{
					var body = msg.Body as PHONE_AUTHEN_Request;

					var info = string.Format("({2})话机连接，设备编号:{0}时间:{1}", body.DeviceId.Trim(), DateTime.Now, e.Client.ConnectionId);
					this.UpdateUI(() => { this.listInfo.Items.Add(info); });
				}
				if (msg.Body is ABT_STATUS_Response)
				{
					var body = msg.Body as ABT_STATUS_Response;

					var info = string.Format("({2})话机状态查询成功，设备编号：{0}时间:{1}", body.Device_id.Trim(), DateTime.Now, e.Client.ConnectionId);
					this.UpdateUI(() =>
					              {
					              	var conn = FindConn(e.Client.ConnectionId);
					              	if (conn == null)
					              	{

					              		conn = new Connection();
					              		conn.Text = body.Device_id + "(" + e.Client.ConnectionId + ")";
					              		conn.Id = e.Client.ConnectionId;
					              		conn.Device_id = body.Device_id.Trim();
					              		this.listPhone.Items.Add(conn);
					              	}
					              	this.listInfo.Items.Add(info);
					              });

				}
				if (msg.Body is STDT_CARD_LOGIN_Request)
				{
					var body = msg.Body as STDT_CARD_LOGIN_Request;
					var info = string.Format("({4})收到刷卡登录，设备编号：{0},卡号{1},学生{2} 时间:{3}", body.Device_id.Trim(),
					                         body.CardID.Trim(), body.student_id.Trim(), body.request_time.Trim(), e.Client.ConnectionId);
					this.UpdateUI(() => { this.listInfo.Items.Add(info); });
				}
			}
		}

		private Connection FindConn(int id)
		{
			foreach (Connection conn in this.listPhone.Items)
			{
				if (conn.Id == id)
				{
					return conn;
				}
			}
			return null;
		}

		private void button2_Click(object sender, EventArgs e)
		{
			var bytes = Utility.StringToBytes(this.textBox1.Text);
			var msgs = Message.FromBytes(bytes, true);
		}

        private void Form1_Load(object sender, EventArgs e)
        {
            if (this.btnStart.Text.Equals("开启服务")) 
            {
                btnStart_Click(sender, e);
            }
        }


	}

	public class ListBoxEx : ListBox
	{
		public new void RefreshItem(int index)
		{
			base.RefreshItem(index);
		}

		public new void RefreshItems()
		{
			base.RefreshItems();
		}
	}
}
